import 'dart:async';

import 'package:flutter/material.dart';

import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/util/log_utils.dart';
import 'package:flutter_deer/widgets/progress_dialog.dart';

mixin BasePageMvvm<T extends StatefulWidget> on State<T> {
  // 创建 StreamController 来管理 Stream
  final StreamController<int> loadingController = StreamController<int>.broadcast();

  // 暴露 Stream 供外部监听
  Stream<int> get loadingStream => loadingController.stream;

  bool _isShowDialog = false;

  void showProgress() {
    /// 避免重复弹出
    if (mounted && !_isShowDialog) {
      _isShowDialog = true;
      try {
        showDialog<void>(
          context: context,
          barrierDismissible: false,
          barrierColor: const Color(0x00FFFFFF), // 默认dialog背景色为半透明黑色，这里修改为透明（1.20添加属性）
          builder: (_) {
            return WillPopScope(
              onWillPop: () async {
                // 拦截到返回键，证明dialog被手动关闭
                _isShowDialog = false;
                return Future.value(true);
              },
              child: buildProgress(),
            );
          },
        );
      } catch (e) {
        /// 异常原因主要是页面没有build完成就调用Progress。
        debugPrint(e.toString());
      }
    }
  }

  void closeProgress() {
    if (mounted && _isShowDialog) {
      _isShowDialog = false;
      NavigatorUtils.goBack(context);
    }
  }

  /// 可自定义Progress
  Widget buildProgress() => const ProgressDialog(hintText: '正在加载...');

  @override
  void didChangeDependencies() {
    Log.d('$T ==> didChangeDependencies');
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    loadingController.close();
    Log.d('$T ==> dispose');
    super.dispose();
  }

  @override
  void deactivate() {
    Log.d('$T ==> deactivate');
    super.deactivate();
  }

  @override
  void didUpdateWidget(T oldWidget) {
    Log.d('$T ==> didUpdateWidgets');
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    loadingController.stream.listen((event) {
      if (event > 0) {
        showProgress();
      } else {
        closeProgress();
      }
      Log.d('$T ==> memberInfoStream $event');
    });
    Log.d('$T ==> initState');
    super.initState();
  }
}
